package com.example.template;

import com.example.common.templates.DirectiveHandler;
import com.example.common.templates.TemplateDirective;
import com.example.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 本周热议
 * @author fangyu
 * @version v1.0.0
 * @date 2020/7/22 8:09 下午
 */
@Component
public class HotsTemplate extends TemplateDirective {

    @Autowired
    RedisUtil redisUtil;

    @Override
    public String getName() {
        return "hots";
    }

    @Override
    public void execute(DirectiveHandler handler) throws Exception {

        String weekRankKey = "week:rank";

        Set<ZSetOperations.TypedTuple> zSetRank = redisUtil.getZSetRank(weekRankKey, 0, 6);

        List<Map> hotPosts = new ArrayList<>();

        for (ZSetOperations.TypedTuple typedTuple : zSetRank) {
            Map<String, Object> map = new HashMap<>();
            Object value = typedTuple.getValue();
            String postKey = "rank:post:" + value;

            map.put("id", typedTuple.getValue());
            System.out.println(postKey);
            System.out.println(redisUtil.hget(postKey, "post:title"));
            map.put("title", redisUtil.hget(postKey, "post:title"));
            map.put("commentCount", typedTuple.getScore());
            hotPosts.add(map);
        }
        handler.put(RESULT, hotPosts).render();
    }
}
